//
//  PaymentVC.swift
//  LeTu
//
//  Created by gy on 2024/1/10.
//

import UIKit

class PaymentVC: BaseViewController {

    private var viewModel: PaymentVM
    
    init(scenicModel: ScenicModel) {
        viewModel = PaymentVM(scenicModel: scenicModel)
        super.init()
    }
    override func viewDidLoad() {
        super.viewDidLoad()

        configUI()
        getData()
    }
    private func getData() {
        
        viewModel.vipVM.getVipPriceList(isPayment: true) { [weak self] dialog in
            
            guard let strongSelf = self else { return }
            DispatchQueue.main.async {
                if dialog.code == 200 {
                    strongSelf.viewModel.updateSectionItmes()
                    strongSelf.paymentTableView.reloadData()
                    strongSelf.updateFotterPrice(index: 0)
                    strongSelf.getCounponsData()
                } else {
                    strongSelf.showMessage(message: dialog.message)
                }
            }
        }
        
    }
    private func getCounponsData() {
        viewModel.getCouponList(isLoad: false) { [weak self] dialog in
            
            guard let strongSelf = self else { return }
            DispatchQueue.main.async {
                if dialog.code == 200 {
                    strongSelf.viewModel.updateCouponsItem()
                    strongSelf.footerView.updatePrice("\(strongSelf.viewModel.getFinalPrice())")
                    strongSelf.paymentTableView.reloadData()
                }
            }
        }
    }
    private func updateFotterPrice(index: Int) {
        guard index < viewModel.vipVM.pricesArr.count else { return }
        let priceModel = viewModel.vipVM.pricesArr[index]
        footerView.updatePrice("\(priceModel.productPrice)")
    }
    // MARK: - UIButtonAction
    @objc func payBtnAction() {
        
        let priceModel = viewModel.vipVM.pricesArr[viewModel.currentPriceIndex]
        
        startloading()
        ApplePayManager.shared.requesProductInfo(productId: priceModel.productId, purchaseType: Int64(priceModel.type), orderMoney: Float(priceModel.productPrice)) { [weak self] in
            guard let strongSelf = self else { return }
            DispatchQueue.main.async {
                strongSelf.stoploading()
                strongSelf.backAction()
                kUserManager.getUserInfomation { dialog in
                    DispatchQueue.main.async {
                        NotificationCenter.default.post(name: NSNotification.Name("PaymentSuccessNotification"), object: nil)
                    }
                }
            }
        } requestProductSuccess: {} failure: { [weak self] in
            guard let strongSelf = self else { return }
            DispatchQueue.main.async {
                strongSelf.stoploading()
                strongSelf.showMessage(message: "支付失败，请重试！")
            }
        }
        
    }
    
    // MARK: - configUI
    func configUI() {
        
        navIsHidden = false
        title = "解锁故事".localized
        
        view.addSubview(paymentTableView)
        view.addSubview(footerView)
        
        paymentTableView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        footerView.snp.makeConstraints { make in
            make.left.bottom.right.equalToSuperview()
            make.height.equalTo(PaymentFooterView.getViewHeight())
        }
        
        paymentTableView.delegate = self
        paymentTableView.dataSource = self
        paymentTableView.register(cellClass: PaymentScenicTableViewCell.self)
        paymentTableView.register(cellClass: PaymentPriceTableViewCell.self)
        paymentTableView.register(cellClass: PaymentCouponTableViewCell.self)
        
    }
    private lazy var paymentTableView: UITableView = {
        let paymentTableView = UITableView()
        paymentTableView.tableFooterView = UIView()
        paymentTableView.backgroundColor = .app_viewBackgroundColor
        return paymentTableView
    }()
    private lazy var footerView = PaymentFooterView(target: self, action: #selector(payBtnAction))
    
    
    required public init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

extension PaymentVC: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return viewModel.sectionItems[section].title == "优惠券" ? 0 : 10
    }
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let footer = UIView(frame: CGRect(x: 0, y: 0, width: screenWidth, height: 10))
        footer.backgroundColor = UIColor.hex(hexString: "#F8F8F8")
        return footer
    }
    func numberOfSections(in tableView: UITableView) -> Int {
        return viewModel.sectionItems.count
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let item = viewModel.sectionItems[indexPath.section]
        if item.title == "景区" {
            return PaymentScenicTableViewCell.getCellHeight()
        } else if item.title == "价格" {
            return PaymentPriceTableViewCell.getCellHeight()
        }
        return 48
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let item = viewModel.sectionItems[section]
        return item.title == "价格" ? viewModel.vipVM.pricesArr.count:1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let item = viewModel.sectionItems[indexPath.section]

        if item.title == "景区" {
            let cell = tableView.dequeueReusableCell(PaymentScenicTableViewCell.self, indexPath: indexPath)
            cell.setScenicModel(viewModel.scenicModel)
            return cell
        } else if item.title == "价格" {
            let cell = tableView.dequeueReusableCell(PaymentPriceTableViewCell.self, indexPath: indexPath)
            cell.setPriceModel(viewModel.vipVM.pricesArr[indexPath.row], isSelect: indexPath.row == viewModel.currentPriceIndex)
            return cell
        }
        let cell = tableView.dequeueReusableCell(PaymentCouponTableViewCell.self, indexPath: indexPath)
        cell.setCouponsModel(viewModel.couponsModel ?? MineCouponsModel())
        return cell
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        let item = viewModel.sectionItems[indexPath.section]
        guard item.title == "价格" else { return }
        viewModel.currentPriceIndex = indexPath.row
        viewModel.updateCouponsItem()
        tableView.reloadData()
        updateFotterPrice(index: indexPath.row)
        footerView.updatePrice("\(viewModel.getFinalPrice())")
        
    }
    
}

